<?php

    /*
     * @ var $owner - указывает на экземпляр класса модели, в которой используется поведения: $this->getOwner()
     */

class MultiLanguageBehavior extends CBehavior
{
    protected $__model;
    private $__langModel, $__languages, $__newSetting=false, $__multiLangModels=array();

    public function getMultiLangModels($forDelete=false)
    {
        if(!$forDelete){
            return $this->__multiLangModels;
        }else{
            return MultiLanguage::model()->findAllByAttributes(array(
                'columnId'=>$this->owner->id,
                'essenceName'=>$this->owner->tableName(),
            ));
        }
    }

    public function setMultiLangModels($models)
    {
        if(is_object($models)) $models=array($models);

        if(sizeof($models)>0){
            foreach($models as $model){
                if(is_object($model) && get_class($model)===get_class($this->multiLangModel)){
                    $this->__multiLangModels[]=$model;
                }
            }
        }
    }

    public function getMultiLangModel($params=array()){
        if(isset($params['code'])){
            $code=$params['code'];
            unset($params['code']);
        }else{
            $code=Yii::app()->language;
        }

        if(isset($params['name'])){
            $name=$params['name'];
            unset($params['name']);
        }else{
            $name=isset($params['columnName']) ? $params['columnName'] : $this->owner->name;
        }
        $params['columnName']=$name;

        if(!isset($params['columnId'])) $params['columnId']=$this->owner->id;
        if(!isset($params['lang'])) $params['lang']=$code;
        if(!isset($params['essenceName'])) $params['essenceName']=$this->owner->tableName();

        $model=MultiLanguage::model()->findByAttributes($params);
        if($model===null) $model=new MultiLanguage();

        return $model;
    }

    public function getIsNewSetting()
    {
        return $this->__newSetting;
    }

    public function getModel()
    {
        if($this->__model===null) $this->__model=new MultiLanguage();
        return $this->__model;
    }

    public function getLanguages()
    {
        if($this->__languages===null) $this->__languages=$this->getLangModel()->all;
        return $this->__languages;
    }

    public function getLangModel($code='')
    {
        if(!$code) $code=Yii::app()->language;
        if($this->__langModel===null){
            $attributes=array(
                'code'=>$code,
            );

            $this->__langModel=Language::model()->findByAttributes($attributes);
        }
        return $this->__langModel;
    }

    public function getDefault()
    {
        return Setting::getConfig('default_language');
    }

    public function translate($name,$lang='')
    {
        if(!$lang) $lang=Yii::app()->language;

        $result=$this->getModel()->findByAttributes(array(
            'essenceName'=>$this->owner->tableName(),
            'columnName'=>$name,
            'columnId'=>$this->owner->id,
            'lang'=>$lang,
        ));

        if($result!==null) return $result->value;
        else return false;
    }

    public function getName()
    {
        $name=$this->translate('name');
        return $name ? $name : Yii::t('main','new');
    }

    public function getValue()
    {
       $shortName='value';
       $longName=$this->owner->tableName().'Value';

       $result=$this->translate($longName);
       if(!$result) $result=$this->translate($shortName);
       if(!$result) $result=$this->owner->$shortName;
       if(!$result) $result=$this->owner->$longName;

       return $result;
    }

    public function getDescription()
    {
       return $this->translate('description');
    }

    public function setAttr($data)
    {
        $model=$this->owner;
        foreach($data as $name=>$value){

            $methodName='set'.ucfirst($name);

            if(method_exists($model,$methodName)){
                $model->$methodName($value);
                unset($data[$name]);
            }elseif(property_exists($model,$name)){
                $model->$name=$value;
                unset($data[$name]);
            }elseif(is_array($value)){
                $this->setMultiLangValues($name,$model,$value);
                unset($data[$name]);
            }
        }

        $model->attributes=$data;
    }

    public function setMultiLangValues($name='',$model=null,$values=array())
    {
        if(!$name || !is_string($name)){
            Yii::app()->notification->error=Yii::t('error','invalidParam',array('{class}'=>__CLASS__,'{param}'=>'name','{method}'=>__METHOD__));
            return false;
        }

        if(is_array($model) && !$values){
            $values=$model;
            $model=$this->owner;
        }elseif(!$model && $values){
            $model=$this->owner;
        }

        if(!$model || !$values){
            Yii::app()->notification->error=Yii::t('error','invalidParam',array('{class}'=>__CLASS__,'{param}'=>'model','{method}'=>__METHOD__));
            return false;
        }

        foreach($values as $code=>$value){
            $attributes=array(
                'columnId'=>$model->id,
                'lang'=>$code,
                'essenceName'=>$model->tableName(),
                'columnName'=>$name,
            );

            $langModel=MultiLanguage::model()->findByAttributes($attributes);

            if($langModel===null){
                $langModel=new MultiLanguage();
                $langModel->attributes=$attributes;
            }
            $langModel->value=$value;

            $this->multiLangModels=$langModel;
        }

        unset($attributes);

        return $values[$this->default];
    }

    public function afterSave()
    {
        $result=true;
        if($this->multiLangModels) $result=$this->afterSaveFunction($this->multiLangModels,$this->owner->id,'columnId');
        return $result;
    }

    public function afterSaveFunction($models,$id,$columnName)
    {
        $result=true;
        $transactionAlreadyExist=false;

        if($this->owner->dbConnection->currentTransaction===null) $transaction=Yii::app()->db->beginTransaction();
        else{
            $transactionAlreadyExist=true;
            $transaction=$this->owner->dbConnection->currentTransaction;
        }

        foreach($models as $model){
            try{
                if(!$model->$columnName) $model->$columnName=$id;

                $model->save();

                if($error=$model->errors){
                    Yii::app()->notification->error=$error;
                    $transaction->rollBack();
                    $result=false;
                    break;
                }
            }catch(Exception $e){
                Yii::app()->notification->error=$e->getMessage();
                $transaction->rollBack();
                $result=false;
                break;
            }
        }

        if($result && !$transactionAlreadyExist) $transaction->commit();
        return $result;
    }
}